package com.softserveinc;

import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItem;
import android.support.v4.view.Window;
import android.util.Log;
import android.view.View;

import com.softserveinc.appwidget.MovieManagerWidgetProvider;
import com.softserveinc.data.MovieDataManager;
import com.softserveinc.fragments.AbstractListFragment;
import com.softserveinc.fragments.CinemaMapFragment;
import com.softserveinc.fragments.CinemaSchemaFragment;
import com.softserveinc.fragments.MovieDetailsFragment;
import com.softserveinc.fragments.MovieListStorageFragment;
import com.softserveinc.fragments.MovieSearchListFragment;
import com.softserveinc.fragments.map.MovieItemizedOverlay;
import com.softserveinc.model.Movie;

public class MovieManagerActivity extends FragmentActivity implements
		AbstractListFragment.OnListItemClickListener,
		MovieDataManager.ProgressCallBack,
		MovieDetailsFragment.OnImageClickListener,
		MovieItemizedOverlay.OnItemTapListener {

	public static final String ACTION_MOVIE_DETAILS = "com.softserveinc.MOVIE_DETAILS";

	public static final int PREFERENCE_RESULT_CONFIRM = 0;
	public static final int PREFERENCE_RESULT_CANCEL = 1;

	protected static final String TAG = MovieManagerActivity.class
			.getSimpleName();

	private Fragment fragment;

	private MovieManagerApplication application;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		setTheme(R.style.Theme_SherlockCustom);

		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		application = (MovieManagerApplication) getApplicationContext();
		application.getDataManager().setProgressCallBack(this);

		if (fragment == null) {
			Intent intent = getIntent();

			if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
				String query = intent.getStringExtra(SearchManager.QUERY);
				processSearch(query);

			} else if (ACTION_MOVIE_DETAILS.equals(intent.getAction())) {
				findViewById(R.id.frame_for_fragment).setVisibility(
						View.VISIBLE);
				processCallFromWidget(intent);
			} else {
				addMovieListIfNeeded();
			}
		}
	}

	@Override
	public void onConfigurationChanged(final Configuration newConfig) {
		Log.i(TAG, "configuration");
		super.onConfigurationChanged(newConfig);

		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			findViewById(R.id.advertisement).setVisibility(View.GONE);
		} else {
			findViewById(R.id.advertisement).setVisibility(View.VISIBLE);
		}
	}

	private void processCallFromWidget(final Intent intent) {
		FragmentManager fragmentManager = getSupportFragmentManager();

		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();

		Bundle bundle = new Bundle();
		bundle.putParcelable(
				MovieDetailsFragment.MOVIE_PARAM_NAME,
				intent.getParcelableExtra(MovieManagerWidgetProvider.APPWIDGET_DISPLAYED_MOVIE));

		fragment = new MovieDetailsFragment();
		fragment.setArguments(bundle);

		if (fragmentManager.findFragmentById(R.id.frame_for_fragment) == null) {
			fragmentTransaction.add(R.id.frame_for_fragment, fragment);
		}

		fragmentTransaction.commit();
	}

	private void addMovieListIfNeeded() {
		FragmentManager fragmentManager = getSupportFragmentManager();

		if (fragmentManager.findFragmentById(R.id.frame_for_fragment) == null) {
			FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();

			fragment = new MovieListStorageFragment();

			fragmentTransaction.add(R.id.frame_for_fragment, fragment);

			fragmentTransaction.commit();
		}
	}

	private void processSearch(final String query) {
		FragmentManager fragmentManager = getSupportFragmentManager();

		if (fragmentManager.findFragmentById(R.id.frame_for_fragment) == null) {
			FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();

			Bundle bundle = new Bundle();
			bundle.putString(MovieSearchListFragment.SEARCH_KEY_PARAM, query);

			fragment = new MovieSearchListFragment();
			fragment.setArguments(bundle);

			fragmentTransaction.add(R.id.frame_for_fragment, fragment);

			fragmentTransaction.commit();
		}
	}

	@Override
	public boolean onSearchRequested() {
		super.onSearchRequested();

		return application.getHardwareManager().isNetworkConnected();
	}

	private void addMapViewIfNeeded() {
		FragmentManager fragmentManager = getSupportFragmentManager();

		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();

		Fragment fragment = new CinemaMapFragment();

		fragmentTransaction.replace(R.id.frame_for_fragment, fragment);

		fragmentTransaction.addToBackStack(null);

		fragmentTransaction.commit();
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_search:
			onSearchRequested();
			return true;

		case R.id.menu_settings:
			Intent intent = new Intent(this,
					MovieManagerPreferenceActivity.class);
			startActivityForResult(intent, PREFERENCE_RESULT_CONFIRM);

			return true;
		case R.id.menu_show_map:
			addMapViewIfNeeded();

			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onItemTap() {
		FragmentManager fragmentManager = getSupportFragmentManager();

		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();

		Fragment fragment = new CinemaSchemaFragment();

		fragmentTransaction.replace(R.id.frame_for_fragment, fragment);

		fragmentTransaction.addToBackStack(null);

		fragmentTransaction.commit();
	}

	@Override
	public void processListItemClick(final Movie movie) {
		FragmentManager fragmentManager = getSupportFragmentManager();

		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();

		Bundle bundle = new Bundle();
		bundle.putParcelable(MovieDetailsFragment.MOVIE_PARAM_NAME, movie);

		fragment = new MovieDetailsFragment();
		fragment.setArguments(bundle);

		fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
				android.R.anim.fade_out);

		fragmentTransaction.replace(R.id.frame_for_fragment, fragment);

		fragmentTransaction.addToBackStack(null);

		fragmentTransaction.commit();
	}

	public void finishFragment(final Fragment fragment) {
		FragmentManager fragmentManager = getSupportFragmentManager();

		fragmentManager.popBackStack();
	}

	@Override
	public void showSpinner() {
		setProgressBarIndeterminateVisibility(Boolean.TRUE);

	}

	@Override
	public void hideSpinner() {
		setProgressBarIndeterminateVisibility(Boolean.FALSE);
	}

	@Override
	public void onImageClick(final String fileName) {
		Intent intent = new Intent();
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setData(Uri.parse(fileName));
		startActivity(intent);
	}

	@Override
	public void showAlertDialog(final String message) {
		new AlertDialog.Builder(this).setMessage(message).setTitle("Warning!")
				.setCancelable(true).setNeutralButton(R.string.button_ok, null)
				.show();
	}
}